package org.zerg.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.zerg.dao.AddressDao;
import org.zerg.dao.OrderDao;
import org.zerg.dao.ProductDao;
import org.zerg.dto.Page;
import org.zerg.entity.Address;
import org.zerg.entity.Order;
import org.zerg.entity.OrderProducts;
import org.zerg.entity.Product;
import org.zerg.entity.User;
import org.zerg.exception.TokenException;
import org.zerg.service.OrderService;

import com.alibaba.fastjson.JSON;

@Service
public class OrderServiceImpl extends BaseServiceImpl implements OrderService{

	@Autowired
	private OrderDao orderDao;
	
	@Autowired
	private ProductDao productDao;
	
	@Value("${adImage.url}")
	private String adImageUrl;
	
	@Autowired
	private AddressDao addressDao;
	
	public String insertOrder(String token, List<OrderProducts> params) {
		//ͨ检测token是否过期
		User user = this.getUserByToken(token);
		if(user==null){
			throw new TokenException("无效的token");
		}
		int uid = user.getId();
		String orderNo = this.getOrderNo(uid);
		Order order = this.OrderSnap(uid, params, orderNo);
		orderDao.insertOrder(order);
		//商品循环存入数据库
		for (OrderProducts products : params) {
			products.setOrderId(orderNo);
		}
		orderDao.insertOrderProducts(params);
		for (OrderProducts Product : params) {
			productDao.cutProduct(Product.getProductId(), Product.getCounts());
		}
		return orderNo;
	}
	
	//数组转换为json字符串，快照
	public Order getOrder(String no) {
		Order order = orderDao.getOrderByNo(no);
		order.setAddress(JSON.parseObject(order.getSnapAddress(), Address.class));
		order.setProducts(JSON.parseArray(order.getSnapItems(), OrderProducts.class));
		order.setSnapItems(null);
		order.setSnapAddress(null);
		return order;
	}

	//生成订单详细信息
	private Order OrderSnap(int uid,List<OrderProducts> params,String orderNo){
		String snapName = null;
		double totalPrice = this.getTotalPrice(params);
		int totalCounts = this.getTotalCounts(params);
		OrderProducts products = params.get(0);
		int pid = products.getProductId();
		String snapImg = adImageUrl+productDao.getProductById(pid).getMainImgUrl();
		if(params.size()>1){
			snapName = productDao.getProductById(pid).getName()+" 等";
		}else{
			snapName = productDao.getProductById(pid).getName();
		}
		List<OrderProducts> list = new ArrayList<OrderProducts>();
		for (OrderProducts orderProducts : params) {
			OrderProducts pp = new OrderProducts();
			pp.setName(productDao.getProductById(orderProducts.getProductId()).getName());
			pp.setPrice(productDao.getProductById(orderProducts.getProductId()).getPrice());
			pp.setCounts(orderProducts.getCounts());
			pp.setMainImgUrl(adImageUrl+productDao.getProductById(orderProducts.getProductId()).getMainImgUrl());
			list.add(pp);
		}
		String snapItems = JSON.toJSONString(list);
		Address address = addressDao.getAddress(uid);
		String snapAddress = JSON.toJSONString(address);
		String creatTime = this.getHTime();
		Order order = new Order(orderNo,uid,creatTime,totalPrice,snapImg,snapName,totalCounts,snapItems,snapAddress);
		return order;
	}
	
	//��ȡ�����ܼ۸�
	private double getTotalPrice(List<OrderProducts> params) {
		double totalPrice = 0;
		for (OrderProducts products : params) {
			Product product = productDao.getProductById(products.getProductId());
			totalPrice = totalPrice + product.getPrice()*products.getCounts();
		}
		return totalPrice;
	}
	
	//��ȡ����������
	private int getTotalCounts(List<OrderProducts> params) {
		int totalCounts = 0;
		for (OrderProducts products : params) {
			totalCounts = totalCounts + products.getCounts();
		}
		return totalCounts;
	}

	//�����ű༭
	private String getOrderNo(int uid) {
		String[] ran = {"A","B","C","D","E","F","G","H","J","K","L","M","N"};
		String orderNo = null;
		Random in = new Random();
		int num = in.nextInt(ran.length);
		String time2 = this.getRandomTime().substring(3);
		String hear = ran[num];
		String time = this.getNowTime();
		orderNo = time2+hear+time+uid;
		return orderNo;
	}


	//分页获取订单
	public List<Order> getOrderPage(String page,String token) {
		User user = this.getUserByToken(token);
		int startpage = Integer.parseInt(page);
		int total = orderDao.getOrderTotal();
		if((startpage-1)*5>total){
			return null;
		}else{
			List<Order> list = orderDao.getOrderPage((startpage-1)*5,user.getId());
			return list;
		}
	}


	public Order getOrderById(int id) {
		Order order = orderDao.getOrderById(id);
		order.setAddress(JSON.parseObject(order.getSnapAddress(), Address.class));
		order.setProducts(JSON.parseArray(order.getSnapItems(), OrderProducts.class));
		order.setSnapItems(null);
		order.setSnapAddress(null);
		return order;
	}

	public List<Order> getOrderAll(int page) {
		//�����Ʒ����
		int total = orderDao.getOrderTotal();
		if((page-1)*15>total){
			return null;
		}
		List<Order> list = orderDao.getOrderAllPage((page-1)*15);
		return list;
	}

	public Page pageMessage(int page) {
		int total = orderDao.getOrderTotal();
		double to = total;
		int totalPage = (int) Math.ceil(to/15);
		Page pa = new Page(page,totalPage,total,15);
		return pa;
	}

	public void setStatus(int classId, int id) {
		orderDao.setStatus(id, classId);
	}


}
